<template>
  <div class="login-bg relative">
    <div class="login-bg-img absolute top-15 left-20">
      <img src="@/assets/images/login-logo.png" alt="login-bg" class="log-img" />
    </div>
    <div class="login-container">
      <!-- 登录页内容 -->
      <div class="login-form relative">
        <div
          v-if="!isRegister"
          class="absolute bottom-5 left-0 w-full text-center flex justify-center"
        >
          <el-checkbox v-model="isAgree"></el-checkbox>
          <el-link :underline="false" class="ml-2">我已阅读并接受</el-link>
          <el-link
            :underline="false"
            type="primary"
            @click="handleAgreement('userServiceAgreement')"
          >
            《用户服务协议》
          </el-link>
          <el-link :underline="false" type="primary" @click="handleAgreement('agreement')">
            《隐私权政策》
          </el-link>
        </div>

        <Register
          v-if="isRegister"
          class="register-box"
          @register="handleRegisterOrLogin(false)"
          @registerSuccess="handleRegisterSuccess"
        />

        <el-tabs v-else v-model="activeName" stretch class="login-tabs">
          <!-- 账号密码登录 ------------------->
          <!-- <el-tab-pane label="账号密码登录" name="countType">
            <el-form
              ref="loginFormRef"
              :model="loginFormData"
              :rules="loginRules"
              class="el-form-box"
            >
              <el-form-item prop="username" class="form-item-class">
                <div class="input-wrapper">
                  <el-icon class="mx-2">
                    <User />
                  </el-icon>
                  <el-input
                    ref="username"
                    v-model="loginFormData.username"
                    :placeholder="$t('login.username')"
                    name="username"
                    size="large"
                    maxlength="11"
                    class="h-[48px]"
                  />
                </div>
              </el-form-item>

              <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
                <el-form-item prop="password" class="form-item-class">
                  <div class="input-wrapper">
                    <el-icon class="mx-2">
                      <Lock />
                    </el-icon>
                    <el-input
                      v-model="loginFormData.password"
                      :placeholder="$t('login.password')"
                      type="password"
                      name="password"
                      size="large"
                      class="h-[48px] pr-2"
                      show-password
                      @keyup.enter="handleLoginSubmit"
                    />
                  </div>
                </el-form-item>
              </el-tooltip>

              <el-form-item prop="captchaCode" class="form-item-class">
                <div class="input-wrapper">
                  <div class="i-svg:captcha mx-2" />

                  <el-input
                    v-model="loginFormData.captchaCode"
                    auto-complete="off"
                    size="large"
                    class="flex-1"
                    :placeholder="$t('login.captchaCode')"
                    @keyup.enter="handleLoginSubmit"
                  />

                  <el-image :src="captchaBase64" class="captcha-img" @click="getCaptcha" />
                </div>
              </el-form-item>
              <LoginButton
                :loading="loading"
                @submit="handleLoginSubmit"
                @login="handleRegisterOrLogin(true)"
                @forget="handleForget"
              />
            </el-form>
          </el-tab-pane> -->
          <!-- 短信登录 ------------------->
          <el-tab-pane label="短信登录" name="smsType">
            <el-form
              ref="loginSmsFormRef"
              :model="loginSmsData"
              :rules="loginSmsRules"
              class="el-form-box"
            >
              <!-- 用户名 -->
              <el-form-item prop="mobile" class="form-item-class">
                <div class="input-wrapper">
                  <el-icon class="mx-2">
                    <User />
                  </el-icon>
                  <el-input
                    ref="mobile"
                    v-model="loginSmsData.mobile"
                    :placeholder="$t('login.mobile')"
                    name="mobile"
                    size="large"
                    class="h-[48px]"
                    maxlength="11"
                  />
                </div>
              </el-form-item>

              <!-- 密码 -->
              <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
                <el-form-item prop="smsCode" class="form-item-class">
                  <div class="input-wrapper">
                    <el-icon class="mx-2">
                      <Lock />
                    </el-icon>
                    <el-input
                      v-model="loginSmsData.smsCode"
                      :placeholder="$t('login.code')"
                      size="large"
                      class="h-[48px] pr-2"
                      @keyup.enter="handleLoginSubmit"
                    >
                      <template #append>
                        <CodeButton
                          :mobile="loginSmsData.mobile"
                          smsType="LOGIN"
                          :validateFunction="validateFunction"
                          @getCode="(smsCode: any) => (loginSmsData.smsCode = smsCode)"
                        />
                      </template>
                    </el-input>
                  </div>
                </el-form-item>
              </el-tooltip>
              <!-- 登录按钮 -->
              <LoginButton
                :loading="loading"
                @submit="handleSmsLoginSubmit"
                @login="handleRegisterOrLogin(true)"
                @forget="handleForget"
              />
              <!-- <el-button
                :loading="loading"
                type="primary"
                size="large"
                class="w-full"
                @click.prevent="handleSmsLoginSubmit"
              >
                {{ $t("login.login") }}
              </el-button> -->
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <Agreement
      ref="AgreementRef"
      :keys="'merchantAgreement'"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    ></Agreement>
    <Agreement
      ref="privacyPolicyRef"
      :keys="'merchantUserServiceAgreement'"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    ></Agreement>
    <forget-password v-if="visible" v-model="visible"></forget-password>
  </div>
</template>

<script setup lang="ts">
import { LocationQuery, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import AuthAPI, { type LoginFormData } from "@/api/auth";
import { getUserStatus } from "@/api/myIndex/index";
import router from "@/router";
import CodeButton from "@/components/SmsCode/CodeButton.vue";
import LoginButton from "./register/components/LoginButton.vue";
import Register from "./register/index.vue";
import type { FormInstance } from "element-plus";
import { OccupiedStatusEnum } from "@/enums/occupied";
import { useUserStore, useDictStore } from "@/store";
import { storeSetMerchantStatus, storeGetMerchantStatus } from "@/utils/auth";
import Agreement from "@/components/Agreement/index.vue";
import ForgetPassword from "@/views/login/forget-password/index.vue";

const userStore = useUserStore();
const dictStore = useDictStore();

const route = useRoute();
const { t } = useI18n();
const loginFormRef = ref<FormInstance>();
const loginSmsFormRef = ref<FormInstance>();

const loading = ref(false); // 按钮 loading 状态
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串
const activeName = ref("smsType"); // 当前选中的tab
const isAgree = ref(false); // 是否同意服务条款
// 忘记密码
const visible = ref(false);
/**
 * 注册还是登陆
 */
const isRegister = ref(false);
/**
 * 服务条款
 */
const userAgreementRef = ref();
const privacyPolicyRef = ref();
const AgreementRef = ref();
const agreementKey = ref();
const handleRegisterOrLogin = (bool: boolean) => {
  isRegister.value = bool;
};
// 注册成功
const handleRegisterSuccess = () => {
  isRegister.value = false;
  activeName.value = "smsType"; // 直接跳到手机登录
};
const handleAgreement = (val: string) => {
  if (val === "agreement") {
    AgreementRef.value.showModal();
  } else {
    privacyPolicyRef.value.showModal();
  }
};

const handleConfirm = () => {
  isAgree.value = true;
};
const handleCancel = () => {
  isAgree.value = false;
};
/**
 * 短信登录
 *
 *
 */
const loginSmsData = ref({
  mobile: "",
  smsCode: "",
  type: 2,
});
const loginSmsRules = computed(() => {
  return {
    mobile: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.mobile.required"),
      },
      {
        validator: (rule: any, value: string, callback: any) => {
          if (!value) {
            callback(new Error("手机号不能为空"));
          } else if (!/^1[3456789]\d{9}$/.test(value)) {
            callback(new Error("请输入正确的手机号"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    smsCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.code.required"),
      },
    ],
  };
});

const validateFunction = async (mobile: string) => {
  console.log(mobile);
  const result = await loginSmsFormRef.value?.validateField("mobile", (valid) => {
    if (valid) {
      console.log("valid");
      return true;
    } else {
      ElMessage.error("请输入有效的手机号码");
      return false;
    }
  });
  console.log(result);
  return result;
};

const handleSmsLoginSubmit = async () => {
  console.log("短信登录", "loginSmsData.value");
  if (!handleAgree()) {
    return;
  }
  loginSmsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        await userStore.smsLogin(loginSmsData.value);
        afterLogin();
      } catch (error) {
        console.log(error);
      } finally {
        loading.value = false;
      }
    }
  });
};
/**
 *
 * 账号密码登录
 *
 *
 *
 */
const loginFormData = ref<LoginFormData>({
  username: "",
  password: "",
  captchaKey: "",
  captchaCode: "",
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

// 获取验证码
function getCaptcha() {
  AuthAPI.getCaptcha().then((data: any) => {
    loginFormData.value.captchaKey = data.data.captchaKey;
    captchaBase64.value = data.data.captchaBase64;
  });
}
function handleAgree() {
  if (!isAgree.value) {
    ElMessage.warning("请先同意服务条款后登录");
    return false;
  } else {
    return true;
  }
}
// 登录
async function handleLoginSubmit() {
  console.log("账号登录", "loginFormData.value");
  if (!handleAgree()) {
    return;
  }
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginFormData.value)
        .then(async () => {
          afterLogin();
        })
        .catch(() => {
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}
async function afterLogin() {
  // 获取用户身份,存储起来
  await funcGetMerchantStatus();
  let merchantStatus = storeGetMerchantStatus();
  await userStore.getUserInfo(); // me的接口
  // 需要在路由跳转前加载字典数据，否则会出现字典数据未加载完成导致页面渲染异常
  await dictStore.loadDictionaries();
  // 根据商户状态跳转 - merchantStatus
  // -1 去完善：点击进入我的主页，展示资质信息页面，上传资质信息
  // 0 审核中：用户提交了资质信息，等待平台审核，页面为空，提示“你的信息已上传，请等待耐心审核”
  // 1 驳回：用户提交了资质信息，平台驳回，页面为空，提示“你的信息已驳回，驳回理由XXXX，请重新提交”
  // 2 重新提交：点击进入我的主页，回显上次提交的信息，在原基础上进行修改
  if (merchantStatus !== OccupiedStatusEnum.TO_FILL) {
    await router.push({ path: "/redirect" });
    hasRoute();
  } else {
    // 跳转到登录前的页面
    const { path, queryParams } = parseRedirect();
    router.push({ path: path, query: queryParams });
    console.log(path, queryParams, "path, queryParams");
  }
}

/**
 *  优先跳转-> 机会列表、我的主页、个人中心
 */
function hasRoute() {
  if (router.hasRoute("Opportunity")) {
    router.push({ name: "Opportunity" });
  } else if (router.hasRoute("Hide")) {
    router.push({ name: "Hide" });
  } else {
    router.push({ name: "Profile" });
  }
}
// async function getUserIdentity() {
//   AuthAPI.getUserIdentity({
//     username: loginFormData.value.username,
//     password: loginFormData.value.password,
//   }).then((data) => {
//     console.log(data);
//     // 存储用户身份
//     storeSetUserIdentity(data);
//     // 如果有用户身份可以切换就显示弹窗
//     storeSetSelectIdentityVisible(true);
//   });
// }
/**
 * 获取当前页面的状态
 *
 */
// status
// "-1": "未找到": 说明要填写资料
//   0: "未审核": 资料还在等待审批
//   1: "入驻通过": 资料审核通过
//   2: "入驻失败": 资料审核失败, 需要重新填写
const funcGetMerchantStatus = async () => {
  try {
    const data = await getUserStatus();
    storeSetMerchantStatus(data.data.status);
    // 如果审核失败，就会有info的信息存储
    if (data?.data.info) {
      console.log(data?.data.info, "data?.info");
      userStore.setUserSettleInfo(data?.data.info);
    } else {
      userStore.setUserSettleInfo(null);
    }
  } catch (err) {
    console.log(err, "getUserStatus");
  }
};
/**
 * 解析 redirect 字符串 为 path 和  queryParams
 *
 * @returns { path: string, queryParams: Record<string, string> } 解析后的 path 和 queryParams
 */
function parseRedirect(): {
  path: string;
  queryParams: Record<string, string>;
} {
  const query: LocationQuery = route.query;
  const redirect = (query.redirect as string) ?? "/";

  const url = new URL(redirect, window.location.origin);
  const path = url.pathname;
  const queryParams: Record<string, string> = {};

  url.searchParams.forEach((value, key) => {
    queryParams[key] = value;
  });

  return { path, queryParams };
}

function handleForget() {
  visible.value = true;
}

onMounted(() => {
  getCaptcha();
});
</script>

<style lang="scss" scoped>
.login-bg {
  width: 100%;
  height: 100%;
  background: #dee9fc;
  .login-bg-img {
    .log-img {
      width: 339px;
      height: 127px;
    }
  }
}

.login-container {
  display: flex;
  align-items: center;
  justify-content: right;
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  background: url("@/assets/images/login-bg.jpg") no-repeat;
  background-size: 100% 100%;
  background-position: center bottom;
  /* 针对 4K 屏幕的媒体查询 */
  @media (min-width: 3840px) {
    width: 25vw; /* 调整宽度 */
  }
  .login-form {
    display: flex;
    justify-content: center;
    //height: 70%;
    padding: 40px;
    margin-right: 5%;
    overflow: hidden;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: var(--el-box-shadow-light);
    .register-box {
      width: 35vw;
    }
    .login-tabs {
      width: 30vw;
      .el-form-box {
        margin: 20px 0 40px;
        .form-item-class {
          margin-bottom: 30px;
        }

        :deep(.el-form-item) {
          background: var(--el-input-bg-color);
          border: 1px solid var(--el-border-color);
          border-radius: 5px;
        }

        :deep(.el-input) {
          .el-input__wrapper {
            padding: 0;
            background-color: transparent;
            box-shadow: none;

            &.is-focus,
            &:hover {
              box-shadow: none !important;
            }

            input:-webkit-autofill {
              /* 通过延时渲染背景色变相去除背景颜色 */
              transition: background-color 1000s ease-in-out 0s;
            }
          }
        }
      }
    }
    @media (width <=460px) {
      width: 100%;
      padding: 20px;
    }
    .input-wrapper {
      display: flex;
      align-items: center;
      width: 100%;
    }

    .captcha-img {
      height: 48px;
      cursor: pointer;
      border-top-right-radius: 6px;
      border-bottom-right-radius: 6px;
    }

    .third-party-login {
      display: flex;
      justify-content: center;
      width: 100%;
      color: var(--el-text-color-secondary);

      *:not(:first-child) {
        margin-left: 20px;
      }

      .icon {
        cursor: pointer;
      }
    }
  }

  .login-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 10px 0;
    text-align: center;
  }
}

html.dark {
  .login {
    background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;

    .login-form {
      background: transparent;
      box-shadow: var(--el-box-shadow);
    }
  }
}
:deep(.el-input-group__append) {
  box-shadow: none !important;
  background-color: transparent !important;
  border-left: 1px solid var(--el-border-color) !important;
}
</style>
